<template>
  <view class="workbench-container">
    <view class="workbench-tabs">
      <view 
        class="tab-item" 
        :class="{ 'active': activeTab === '我的任务' }"
        @click="activeTab = '我的任务'"
      >我的任务</view>
      <view 
        class="tab-item" 
        :class="{ 'active': activeTab === '接单中心' }"
        @click="activeTab = '接单中心'"
      >接单中心</view>
    </view>

    <!-- 未绑定仓库提示 -->
    <view v-if="!hasWarehouse" class="no-warehouse-tip">
      <text class="tip-text">您尚未绑定仓库</text>
      <text class="tip-subtitle">请联系管理员分配所属仓库</text>
    </view>

    <!-- 我的任务 -->
    <view v-else-if="activeTab === '我的任务'" class="order-list">
      <view 
        v-for="(order, index) in sortedOrderList" 
        :key="index" 
        class="available-order-item"
        :class="{'order-completed': order.status === 1}"
      >
        <view class="available-order-header">
          <text class="available-order-number">订单号：{{ order.orderId }}</text>
          <text class="available-order-time">{{ order.createTime }}</text>
        </view>
        <view class="available-order-location">
          <text>{{ order.cityName }}{{ order.districtName }}（{{ order.address }}）</text>
        </view>
        <view class="available-order-contact">
          <text class="contact-info">
            {{ order.userName || '未知用户' }} 
            {{ order.phone || '未知电话' }}
          </text>
          <view class="order-footer">
            <text class="order-quantity">商品：{{ order.quantity }}件</text>
            <view class="order-actions">
              <text 
                class="action-btn detail-btn" 
                @click="showGoodsDetail(order)"
              >商品明细</text>
              <text 
                v-if="order.status === 0" 
                class="action-btn complete-btn"
                @click="completeOrder(order)"
              >完成分拣</text>
              <text 
                v-if="order.status === 1" 
                class="action-btn completed-btn"
              >已完成</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 接单中心 -->
    <view v-else-if="activeTab === '接单中心'" class="order-center">
      <view class="order-center-header">
        <text class="order-center-title">可接单数量：{{ availableOrderCount }}</text>
      </view>
      <view class="available-order-list">
        <view 
          v-for="(order, index) in availableOrders" 
          :key="index" 
          class="available-order-item"
          :class="{'order-selected': isOrderSelected(order)}"
        >
          <view class="available-order-content">
            <view class="available-order-header">
              <text class="available-order-number">订单号：{{ order.orderId }}</text>
              <text class="available-order-time">{{ order.createTime }}</text>
            </view>
            <view class="available-order-location">
              <text>{{ order.cityName }}{{ order.districtName }}（{{ order.address }}）</text>
            </view>
            <view class="available-order-contact">
              <text class="contact-info">
                {{ order.userName || '未知用户' }} 
                {{ order.phone || '未知电话' }}
              </text>
              <view class="order-footer">
                <text class="order-quantity">商品：{{ order.quantity }}件</text>
              </view>
            </view>
          </view>
          <view 
            class="order-checkbox" 
            @click="toggleOrderSelection(order)"
          >
            <text class="checkbox" :class="{'checked': isOrderSelected(order)}"></text>
          </view>
        </view>
      </view>
      
      <!-- 底部选择栏 -->
      <view class="bottom-selection-bar">
        <view 
          class="select-all-btn" 
          @click="toggleSelectAllOrders"
        >
          <text class="checkbox" :class="{'checked': isAllOrdersSelected}"></text>
          <text>全选</text>
        </view>
        <text 
          class="receive-all-btn" 
          @click="receiveSelectedOrders"
          :class="{'disabled': selectedOrders.length === 0}"
        >一键接单</text>
      </view>
    </view>

    <!-- 商品明细弹窗 -->
    <uni-popup ref="goodsDetailPopup" type="center">
      <view class="goods-detail-popup">
        <view class="popup-header">
          <text>商品明细</text>
          <text class="close-btn" @click="closeGoodsDetail">×</text>
        </view>
        <view class="goods-list">
          <view 
            v-for="(goods, index) in currentOrderGoods" 
            :key="index" 
            class="goods-item"
          >
            <text class="goods-name">{{ goods.productName }}</text>
            <text class="goods-quantity">数量：{{ goods.quantity }}</text>
          </view>
        </view>
        <view class="goods-total">
          <text>合计</text>
          <text>数量：{{ totalGoodsQuantity }}</text>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { request } from '@/utils/request'

export default {
  data() {
    return {
      activeTab: '我的任务',
      orderList: [],
      availableOrders: [],
      availableOrderCount: 0,
      currentOrderGoods: [],
      hasWarehouse: true,
      warehouseId: null, // 新增仓库ID字段
      selectedOrders: [], // Track selected orders
      isAllOrdersSelected: false, // Flag for all orders selection
    }
  },
  computed: {
    sortedOrderList() {
      if (!this.orderList) return []
      
      // 先按状态排序（未完成在前），再按创建时间倒序
      return this.orderList
        .sort((a, b) => {
          // 未完成的订单（status === 0）优先排序
          if (a.status === 0 && b.status === 1) return -1
          if (a.status === 1 && b.status === 0) return 1
          
          // 状态相同时，按创建时间倒序
          return new Date(b.createTime) - new Date(a.createTime)
        })
    },
    totalGoodsQuantity() {
      return this.currentOrderGoods.reduce((total, goods) => total + goods.quantity, 0)
    }
  },
  onShow() {
    this.checkWarehouseBinding()
  },
  methods: {
    async checkWarehouseBinding() {
      try {
        const res = await request({
          url: '/sorter/profile',
          method: 'GET',
          data: {
            sorterAccount: uni.getStorageSync('sorterAccount')
          }
        })

        if (res.code === 200) {
          // 检查是否有仓库信息
          const warehouseName = res.data.warehouseName || ''
          this.hasWarehouse = !!warehouseName.trim()
          
          // 获取仓库ID
          this.warehouseId = res.data.warehouseId || null

          if (this.hasWarehouse) {
            this.fetchOrderList()
            this.fetchAvailableOrders()
          } else {
            uni.showModal({
              title: '提示',
              content: '您尚未绑定仓库，请联系管理员分配所属仓库',
              showCancel: false,
              confirmText: '确定'
            })
          }
        } else {
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          })
        }
      } catch (err) {
        console.error('仓库绑定检查失败:', err)
        uni.showToast({
          title: '仓库绑定检查失败',
          icon: 'none'
        })
      }
    },
    async fetchOrderList() {
      // 检查是否有仓库ID
      if (!this.warehouseId) {
        uni.showToast({
          title: '未获取到仓库信息',
          icon: 'none'
        })
        return
      }

      try {
        const res = await request({
          url: '/sorter/my-orders',
          method: 'GET',
          data: {
            warehouseId: this.warehouseId
          }
        })
        if (res.code === 200) {
          // 直接使用返回的数据
          this.orderList = res.data
          
          console.log('仓库ID:', this.warehouseId)
          console.log('我的任务订单响应:', res)
        }
      } catch (err) {
        console.error('获取我的任务订单失败:', err)
        uni.showToast({
          title: '获取我的任务订单失败',
          icon: 'none'
        })
      }
    },
    async fetchAvailableOrders() {
      // 检查是否有仓库ID
      if (!this.warehouseId) {
        uni.showToast({
          title: '未获取到仓库信息',
          icon: 'none'
        })
        return
      }

      try {
        const res = await request({
          url: '/sorter/available-orders',
          method: 'GET',
          data: {
            warehouseId: this.warehouseId
          }
        })
        if (res.code === 200) {
          // 直接使用返回的数据，不再假设有 orders 和 total 属性
          this.availableOrders = res.data
          this.availableOrderCount = res.data.length
          
          // 重置选择状态
          this.selectedOrders = []
          this.isAllOrdersSelected = false
          
          console.log('仓库ID:', this.warehouseId)
          console.log('可接订单响应:', res)
        }
      } catch (err) {
        console.error('获取可接订单失败:', err)
        uni.showToast({
          title: '获取可接订单失败',
          icon: 'none'
        })
      }
    },
    async showGoodsDetail(order) {//商品明细
      try {
        const res = await request({
          url: `/sorter/orderGoods`,
          method: 'GET',
          data: {
            orderId: order.orderId // 传递订单ID
          }
        })

        console.log('商品明细响应:', res)

        if (res.code === 200) {
          // 直接使用 res.data，因为返回的是数组
          this.currentOrderGoods = res.data
          this.$refs.goodsDetailPopup.open()
        }
      } catch (err) {
        console.error('获取商品明细失败:', err)
        uni.showToast({
          title: '获取商品明细失败',
          icon: 'none'
        })
      }
    },
    async completeOrder(order) {
      try {
        const res = await request({
          url: `/sorter/myOrderTask`,
          method: 'POST',
          data: {
            orderId: order.orderId, // 传递订单ID
            warehouseId: this.warehouseId // 传递仓库ID
          }
        })

        if (res.code === 200) {
          // 将订单状态更新为已分拣（1）
          order.status = 1
          
          uni.showToast({
            title: '分拣完成',
            icon: 'success'
          })
          
          // 刷新订单列表
          this.fetchOrderList()
        }
      } catch (err) {
        console.error('完成订单失败:', err)
        uni.showToast({
          title: '完成订单失败',
          icon: 'none'
        })
      }
    },
    async receiveOrder(order) {
      try {
        const res = await request({
          url: `/sorter/order/${order.orderNumber}/receive`,
          method: 'POST'
        })

        if (res.code === 200) {
          uni.showToast({
            title: '接单成功',
            icon: 'success'
          })
          // 刷新可接订单和我的任务列表
          this.fetchAvailableOrders()
          this.fetchOrderList()
        }
      } catch (err) {
        console.error('接单失败:', err)
        uni.showToast({
          title: '接单失败',
          icon: 'none'
        })
      }
    },
    closeGoodsDetail() {
      this.$refs.goodsDetailPopup.close()
    },
    toggleSelectAllOrders() {
      this.isAllOrdersSelected = !this.isAllOrdersSelected
      if (this.isAllOrdersSelected) {
        this.selectedOrders = this.availableOrders.map(order => order.orderId)
      } else {
        this.selectedOrders = []
      }
    },
    isOrderSelected(order) {
      return this.selectedOrders.includes(order.orderId)
    },
    toggleOrderSelection(order) {
      if (this.isAllOrdersSelected) {
        this.selectedOrders = []
      }
      if (this.selectedOrders.includes(order.orderId)) {
        this.selectedOrders = this.selectedOrders.filter(id => id !== order.orderId)
      } else {
        this.selectedOrders.push(order.orderId)
      }
    },
    async receiveSelectedOrders() {
      // 获取存储的 sorterJWT
      const sorterJWT = uni.getStorageSync('sorterJWT')
      
      // 检查是否有选中的订单和 JWT
      if (this.selectedOrders.length === 0) {
        uni.showToast({
          title: '请选择要接单的订单',
          icon: 'none'
        })
        return
      }

      if (!sorterJWT) {
        uni.showToast({
          title: '登录信息已过期，请重新登录',
          icon: 'none'
        })
        return
      }

      try {
        const res = await request({
          url: '/sorter/receive',
          method: 'POST',
          data: {
            orderIds: this.selectedOrders
          }
        })

        if (res.code === 200) {
          uni.showToast({
            title: '已接收选中的订单',
            icon: 'success'
          })
          this.fetchAvailableOrders()
          this.fetchOrderList()
          
          // 重置选择状态
          this.selectedOrders = []
          this.isAllOrdersSelected = false
        }
      } catch (err) {
        console.error('接收选中的订单失败:', err)
        uni.showToast({
          title: '接收选中的订单失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.workbench-container {
  background-color: #f4f4f4;
  height: 100vh; /* 使用全视窗高度 */
  display: flex;
  flex-direction: column;
  font-size: 12px; /* 全局缩小字体 */
}

.workbench-tabs {
  flex-shrink: 0; /* 不允许tabs压缩 */
  display: flex;
  background-color: white;
  border-bottom: 1px solid #f0f0f0;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  color: #666;
  font-size: 14px;
  position: relative;
}

.tab-item.active {
  color: #007aff;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 3px;
  background-color: #007aff;
}

.order-list, .order-center {
  flex-grow: 1; /* 允许内容区域填充剩余空间 */
  overflow-y: auto; /* 内容区域可滚动 */
  padding: 15px;
  padding-bottom: 60px; /* 为底部操作栏留空间 */
}

.order-item {
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.order-number {
  font-size: 14px;
  color: #666;
}

.order-status {
  color: #f39c12;
  font-size: 14px;
}

.order-info {
  display: flex;
  justify-content: space-between;
  color: #333;
  font-size: 15px;
  margin-bottom: 10px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
}

.order-goods {
  color: #666;
  font-size: 14px;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.order-actions .action-btn {
  font-size: 12px;
  padding: 5px 10px;
  border-radius: 4px;
}

.detail-btn {
  background-color: #f0f0f0;
  color: #333;
}

.complete-btn {
  background-color: #007aff;
  color: white;
}

.goods-detail-popup {
  width: 300px;
  background-color: white;
  border-radius: 10px;
  padding: 15px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: bold;
}

.close-btn {
  color: #999;
  font-size: 24px;
  cursor: pointer;
}

.goods-list {
  max-height: 300px;
  overflow-y: auto;
}

.goods-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.goods-name {
  color: #333;
}

.goods-quantity {
  color: #666;
}

.goods-total {
  display: flex;
  justify-content: space-between;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
  font-weight: bold;
}

.order-center {
  padding: 15px;
  padding-bottom: 100px; /* 为底部选择栏和导航栏留出空间 */
}

.order-center-header {
  background-color: white;
  padding: 10px 15px;
  margin-bottom: 10px;
}

.order-center-title {
  color: #333;
  font-size: 12px;
}

.order-center-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.bottom-selection-bar {
  position: fixed;
  bottom: 0; /* 直接贴在底部 */
  left: 0;
  right: 0;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
  box-shadow: 0 -2px 8px rgba(0,0,0,0.1);
}

.select-all-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.checkbox {
  width: 16px;
  height: 16px;
  border: 1px solid #666;
  border-radius: 4px;
}

.checkbox.checked {
  background-color: #007aff;
}

.receive-all-btn {
  background-color: #007aff;
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
}

.receive-all-btn.disabled {
  background-color: #f0f0f0;
  color: #999;
}

.available-order-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.available-order-item {
  background-color: white;
  padding: 10px;
  margin-bottom: 10px;
  font-size: 12px;
  position: relative;
}

.available-order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.available-order-number {
  color: #333;
  font-weight: bold;
}

.available-order-time {
  color: #999;
}

.available-order-location {
  margin-bottom: 5px;
  color: #666;
}

.available-order-contact {
  display: flex;
  flex-direction: column;
}

.contact-info {
  margin-bottom: 5px;
  color: #333;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-quantity {
  color: #666;
  font-weight: bold;
}

.order-selected {
  background-color: #f0f0f0;
  opacity: 0.7;
}

.order-checkbox {
  position: absolute;
  bottom: 10px;
  right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
}

.checkbox {
  width: 16px;
  height: 16px;
  border: 1px solid #666;
  border-radius: 4px;
  display: inline-block;
}

.checkbox.checked {
  background-color: #007aff;
  border-color: #007aff;
  position: relative;
}

.checkbox.checked::after {
  content: '✓';
  color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 12px;
}

.available-order-content {
  display: flex;
  flex-direction: column;
}

.no-warehouse-tip {
  padding: 20px;
  text-align: center;
  background-color: white;
  border-radius: 10px;
  margin-bottom: 15px;
}

.tip-text {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.tip-subtitle {
  font-size: 12px;
  color: #666;
}

.order-completed {
  background-color: #f0f0f0; /* 更浅的灰色，与页面背景明显区分 */
  border: 1px solid #e0e0e0; /* 添加边框 */
  opacity: 0.8; /* 略微降低透明度 */
}

.order-completed .order-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-completed .action-btn.completed-btn {
  background-color: #f0f0f0;
  color: #999;
  font-size: 12px;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: default; /* 默认光标 */
  pointer-events: none; /* 禁用点击 */
}

.order-completed .available-order-header,
.order-completed .available-order-location,
.order-completed .contact-info {
  color: #999; /* 更浅的文字颜色 */
}

.order-completed .order-quantity,
.order-completed .available-order-number {
  color: #888; /* 略微变浅 */
}

.order-completed .action-btn {
  color: #aaa; /* 操作按钮变得更浅 */
  background-color: #f5f5f5; /* 按钮背景更浅 */
  cursor: not-allowed; /* 禁用光标 */
}

.order-completed .action-btn.detail-btn {
  color: #666; /* 商品明细按钮保持可读性 */
}
</style> 